package cn.xxm.strategy.pay.validate.executor;
import cn.xxm.strategy.pay.i18n.response.CommonResponseInfo;
import cn.xxm.strategy.pay.validate.processor.ValidateProcessor;
import cn.xxm.strategy.pay.validate.response.ValidatorResult;
import org.springframework.cglib.reflect.FastMethod;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * @author xxm
 * @create 2020-11-19 15:34
 */
@Component
public class GenericValidatorExecutor extends AbstractValidatorExecutor {

    @Override
    protected ValidatorResult<?> doValidate(Object value) throws InvocationTargetException {
        ValidatorResult result = new ValidatorResult<CommonResponseInfo>();
        Class<?> clazz = value.getClass();
        ValidatorExecuterDelegate validatorExecuterDelegate = getValidatorExecuterCache(clazz);
        Map<FastMethod, List<ValidateProcessor>> validPropertyCache = validatorExecuterDelegate.getValidPropertyCache();
        VALIDATE_START:
        for (FastMethod getter : validPropertyCache.keySet()) {
            Object obj;
            obj = getter.invoke(value, null);
            List<ValidateProcessor> processors = validPropertyCache.get(getter);
            for (ValidateProcessor validateProcessor : processors) {
                if (!validateProcessor.validate(obj)) {//校验不通过
                    result.setValid(false);
                    result.setResponseInfo(validateProcessor.getResponseInfo());
                    break VALIDATE_START;//跳出双层循环
                }
            }
        }
        return result;
    }

}
